package start;

import java.io.IOException;
import java.util.Date;
import java.util.Vector;

import IO.Save;

import web.Downloader;
import web.PopulateShow;
import data.Show;
import data.Show.Status;

//@Jen - need a thread suiside method.
/**@quinn - need to learn how to spell suicide */
public class Heartbeat implements Runnable
{
	/**
	 * The show list to check for updates for. 
	 */
	private Vector<Show> showList;

	/**
	 * Constructor
	 * @param showList - shallow copy of the showlist to update.
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public Heartbeat(Vector<Show> showList) throws IOException, InterruptedException
	{
		this.showList = showList;
	}
	
	
	
	/**
	 * Method used to run Heartbeat as a thread. 
	 * Also checks for show updates every hour.
	 */
	public void run()
	{
		boolean alive = true;
		while(alive)
		{
			while(showList.size() == 0);
			for(Show s : showList)
			{
				PopulateShow popShow = new PopulateShow(s.getShowName());

				if(popShow.updateShow(s))
				{
					System.out.println("["+new Date().toString()+" : "+s.getShowName()+"] Show updated!");
					
					//Show has been updated!  If the show wasn't set on CHECK, attempt to goToNext
					if(s.getStatus() != Status.CHECK)
					{
						if(s.goToNextEpisode())
						{
							s.setStatus(Status.CHECK);
						}
					}
				}
				else
				{
					System.out.println("["+new Date().toString()+" : "+s.getShowName()+"] nothing new");
				}
				
				//If the show is set to CHECK, kick off that downloader!
				if(s.getStatus() == Status.CHECK)
				{
					//go-go gadget downloader!
					new Downloader(s);
				}
				
			}
			
			try {
				Save.saveShows(showList);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			try {
				
				Thread.sleep(1000*60*60); // 1 sec * 60 min/sec * 60 hour/min
				//Thread.sleep(1000*30); //30 seconds. For testing.
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
			
		}
	}
}
